<?php
/*读取前端数据*/
$username = trim($_POST['username']); //$_POST是PHP中的全局数组
$usernameReg = '/^[a-zA-Z0-9]{3,10}$/';
if(!preg_match($usernameReg,$username)){
    echo '<script>alert("用户名必填！且只能由大小写、数字构成，长度3-10个字符！");history.back();</script>';
    exit;
}
$pw = trim($_POST['pw']);
$pwReg = "/^[a-zA-Z0-9_*]{6,10}$/";
if(!preg_match($pwReg,$pw)){
    echo '<script>alert("密码必填！且只能由大小写、数字、_、*构成，长度6-10个字符！");history.back();</script>';
    exit;
}
$cpw = trim($_POST['cpw']);
if($pw != $cpw){
    echo '<script>alert("密码和重复密码必须相同！");history.back();</script>';
    exit;
}
$email = trim($_POST['email']);
if($email){
    //如果填了信箱，则需要验证信箱格式
    $emailReg = "/^[a-zA-Z0-9_\-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)/";
    if(!preg_match($emailReg,$email)){
        echo '<script>alert("信箱格式不正确！");history.back();</script>';
        exit;
    }
}
$sex = $_POST['sex'];
if($_POST['fav']){
    $fav = implode("，",$_POST['fav']);
}
else{
    $fav = '';
}
//$pw = md5($pw);

include 'conn.php';
//判断用户名是否被占用
$sql= "select * from userinfo where username = '$username'";
$result = mysqli_query($conn, $sql);
//判断记录集中是否有记录
if(mysqli_num_rows($result)){ //PHP中非零非空即为真
    echo '<script>alert("该用户名已被占用！");history.back();</script>';
    exit;
}
$sql = "insert into userinfo (username,pw,email,sex,fav) values ('$username','" . md5($pw) . "','$email','$sex','$fav')";
$result = mysqli_query($conn,$sql);
/*//第一招：打印SQL语句
echo $sql . "<br>";
//第二招：打印mysql错误信息
echo mysqli_error($conn);
echo "<br>";*/
if($result){
    echo '<script>alert("数据插入成功！");history.back();</script>';
}
else{
    echo '<script>alert("数据插入失败！");history.back();</script>';
}